package com.example.quiz;


import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.example.quiz.model.HttpManager;
import com.example.quiz.model.PacoteRequisicao;
import com.example.quiz.model.Usuario;


public class Inicial extends Activity {
	
	public static String USUARIO = "";
	public static long IDUSUARIO = 0;
	public static int PONTOS = 0;
	public static Usuario usuario = null;
	
	private EditText etUsuario ;
	private EditText etSenha ;
	
	private Tarefa tarefa;
	
	private String autenticacao = null;
	
	private ProgressBar pb;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.inicial);
		
		pb = (ProgressBar) findViewById(R.id.pbInicial);
		pb.setVisibility(View.INVISIBLE);
		
		etUsuario = (EditText)findViewById(R.id.etUsuario);
		etSenha = (EditText)findViewById(R.id.etSenha);		
		etUsuario.requestFocus();
		
		Button btnEntrar = (Button) findViewById(R.id.btnEntrar);		
		btnEntrar.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				if(isOnline()){			
					String usuario = etUsuario.getText().toString();
					String senha = etSenha.getText().toString();
					if(usuario.length()<3 || senha.length()<3){
						Toast.makeText(getApplicationContext(), "Usuario ou senha devem conter pelo menos 3 caracteres", Toast.LENGTH_SHORT).show();
						etUsuario.setText("");
						etSenha.setText("");
						etUsuario.requestFocus();
					}else{	
						pb.setVisibility(View.VISIBLE);						
						tarefa = new Tarefa();
						PacoteRequisicao pacote = new PacoteRequisicao();
						pacote.setMethod("POST");
						pacote.setUri("http://192.168.25.18:8080/QuizServer/ServletLogin");
						pacote.setParametro("usuario", usuario);
						pacote.setParametro("senha", senha);
						tarefa.execute(pacote);			
					}
				}else{
					Toast.makeText(getApplicationContext(), "Rede nao disponivel", Toast.LENGTH_SHORT).show();
				}				
			}
		});
		
		
		Button btnCadastrarSe = (Button) findViewById(R.id.btnCadastrarSe);		
		btnCadastrarSe.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				startActivity(new Intent(Inicial.this, CadastrarSe.class));
			}
		});
		

	}
	private class Tarefa extends AsyncTask<PacoteRequisicao, String, String>{

		@Override
		protected void onPreExecute() {
		}
		
		@Override
		protected String doInBackground(PacoteRequisicao... params) {
			HttpManager hm = new HttpManager();
			try {
				JSONObject json = new JSONObject(hm.getData(params[0]));
				autenticacao = json.getString("message"); 
//				Log.i("logquiz",json.getString("message"));
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}			
			return null;
		}
		
		@Override
		protected void onPostExecute(String result) {			
			pb.setVisibility(View.INVISIBLE);
				
			if(Boolean.parseBoolean(autenticacao)){
				startActivity(new Intent(Inicial.this, MenuPrincipal.class));
				Log.i("logquiz","iniciar");
			}else{
				Toast.makeText(getApplicationContext(), "Usuario ou senha incorretos", Toast.LENGTH_SHORT).show();
				etUsuario.setText("");
				etSenha.setText("");
				etUsuario.requestFocus();
//				Log.i("logquiz","não autenticado");
			}			
		}
		
		@Override
		protected void onProgressUpdate(String... values) {
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
	}
	protected boolean isOnline(){
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netInfo = cm.getActiveNetworkInfo();
		if(netInfo != null && netInfo.isConnectedOrConnecting()){
			
			return true;
		}else{
			return false;
		}
	}
}
